var Promise = require('bluebird');
var superagent = Promise.promisifyAll(require('superagent'));
var logger = require('superagent-logger');

if (typeof String.prototype.endsWith !== 'function') {
  String.prototype.endsWith = function(suffix) {
    return this.indexOf(suffix, this.length - suffix.length) !== -1;
  };
}

if (typeof String.prototype.startsWith !== 'function') {
  String.prototype.startsWith = function(suffix) {
    return this.indexOf(suffix, 0) !== -1;
  };
}

var getConfig = function(config, auth, clinetIP) {
  try{
    config = config || {};
    config.header = config.header || {};
    auth=auth || '';
    var header= {};

    for (var i in config.header) {
      header[i] = config.header[i];
    }
    header['X-KJT-AUTH']=auth;
    if(clinetIP) header['X-KJT-Agent']=header['X-KJT-Agent'] + ';' + clinetIP;
    return header;
  }catch(ex){
    console.log(ex)
    return {
      "Content-Type":"application/json",
      "X-KJT-Agent": "1234;3333;Android4.4;MIUI7.1;CMCC;Nexus5;001002;2.0.0;WIFI;-",
      "X-KJT-AUTH": "",
      "X-API-VER": "2.0"
    };
  }
}

module.exports = {
  request: function(method, config, url, auth, clinetIP){
    var config = config || {};
    if(config.url === undefined){
      config.url = '';
    }
    var host = config.url.endsWith('/')? config.url: config.url + '/';

    if(url){
      var path = url.startsWith('/') ? url.substr(1,url.length) : url;
    }
    var header = getConfig(config, auth, clinetIP);
    console.log(host + path)
    return superagent[method](host + path)
      .timeout(10000)
      .set(header)
      // .use(logger)
  }
}